from django.shortcuts import render, redirect
from django.contrib import messages
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from .models import TextGenerationRecord, PromptTemplate
from .services.llm_service import DoubaoLLMService, build_enhanced_prompt
import json
import logging

logger = logging.getLogger(__name__)


@login_required
def text_list(request):
    """获取文本生成记录列表API"""
    try:
        # 获取用户（测试时使用默认用户）
        if hasattr(request, 'user') and request.user.is_authenticated:
            user = request.user
        else:
            from django.contrib.auth.models import User
            user, created = User.objects.get_or_create(username='test_user')
        
        # 获取分页参数
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 10))
        
        # 获取用户的所有记录，按创建时间倒序排列
        records = TextGenerationRecord.objects.filter(user=user).order_by('-created_at')
        
        # 计算总数和分页
        total_count = records.count()
        start_index = (page - 1) * page_size
        end_index = start_index + page_size
        page_records = records[start_index:end_index]
        
        # 序列化数据
        records_data = []
        for record in page_records:
            records_data.append({
                'id': record.id,
                'module': record.get_module_display(),
                'content_type': record.get_content_type_display(),
                'language_style': record.get_language_style_display(),
                'prompt': record.prompt,
                'generated_content': record.generated_content,
                'generation_params': record.generation_params,
                'used_model': record.used_model,
                'created_at': record.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'is_favorite': record.is_favorite
            })
        
        return JsonResponse({
            'code': 200,
            'msg': '获取成功',
            'data': {
                'records': records_data,
                'total_count': total_count,
                'current_page': page,
                'page_size': page_size
            }
        })
    except Exception as e:
        logger.error(f"获取文本记录列表异常: {str(e)}")
        return JsonResponse({
            'code': 500,
            'msg': f'服务器内部错误: {str(e)}',
            'data': None
        })


@login_required
@csrf_exempt  # 测试用，生产环境建议配置CSRF
@require_http_methods(["POST"])
def generate_text(request):
    """文本生成API"""
    try:
        # 获取请求参数（支持JSON和form-data两种格式）
        if request.content_type == 'application/json':
            data = json.loads(request.body)
            module = data.get('module')
            content_type = data.get('content_type')
            prompt = data.get('prompt')
            language_style = data.get('language_style', 'casual')
            generation_params = data.get('generation_params', {})
        else:
            module = request.POST.get('module')
            content_type = request.POST.get('content_type')
            prompt = request.POST.get('prompt')
            language_style = request.POST.get('language_style', 'casual')
            generation_params_str = request.POST.get('generation_params', '{}')
            try:
                generation_params = json.loads(generation_params_str) if generation_params_str else {}
            except json.JSONDecodeError:
                generation_params = {}
        
        # 参数验证
        if not all([module, content_type, prompt]):
            return JsonResponse({
                'code': 400,
                'msg': '缺少必要参数：module, content_type, prompt',
                'data': None
            })
        
        # 验证模块类型
        valid_modules = ['creative', 'academic']
        if module not in valid_modules:
            return JsonResponse({
                'code': 400,
                'msg': f'模块类型必须是{valid_modules}之一',
                'data': None
            })
        
        # 验证内容类型
        valid_content_types = ['novel', 'poetry', 'script', 'story', 'copy', 'paper', 'summary', 'reference', 'report']
        if content_type not in valid_content_types:
            return JsonResponse({
                'code': 400,
                'msg': f'内容类型必须是{valid_content_types}之一',
                'data': None
            })
        
        # 验证提示词长度
        if len(prompt.strip()) == 0:
            return JsonResponse({
                'code': 400,
                'msg': '提示词不能为空',
                'data': None
            })
        
        if len(prompt) > 2000:
            return JsonResponse({
                'code': 400,
                'msg': '提示词长度不能超过2000字符',
                'data': None
            })
        
        # 获取用户（测试时使用默认用户）
        if hasattr(request, 'user') and request.user.is_authenticated:
            user = request.user
        else:
            from django.contrib.auth.models import User
            user, created = User.objects.get_or_create(username='test_user')
        
        logger.info(f"用户 {user.username} 请求生成文本，模块: {module}, 类型: {content_type}")
        
        # 创建文本生成记录
        record = TextGenerationRecord.objects.create(
            user=user,
            module=module,
            content_type=content_type,
            language_style=language_style,
            prompt=prompt,
            generation_params=generation_params
        )
        
        # 调用大模型生成文本
        llm_service = DoubaoLLMService()
        
        # 根据内容类型构建更详细的提示词
        enhanced_prompt = build_enhanced_prompt(module, content_type, prompt, generation_params)
        
        # 调用LLM API
        result = llm_service.generate_text(
            prompt=enhanced_prompt,
            max_tokens=generation_params.get('max_tokens', 1000),
            temperature=generation_params.get('temperature', 0.7)
        )
        
        if result['success']:
            generated_content = result['content']
            record.used_model = result['model']
            record.generated_content = generated_content
            record.save()
            
            logger.info(f"文本生成成功，记录ID: {record.id}, 耗时: {result.get('duration', 0):.2f}s")
            
            return JsonResponse({
                'code': 200,
                'msg': '文本生成成功',
                'data': {
                    'id': record.id,
                    'generated_content': generated_content,
                    'used_model': record.used_model,
                    'usage': result.get('usage', {}),
                    'duration': result.get('duration', 0)
                }
            })
        else:
            # 生成失败，记录错误信息
            error_msg = result['error']
            record.generated_content = f"生成失败: {error_msg}"
            record.save()
            
            logger.error(f"文本生成失败，记录ID: {record.id}, 错误: {error_msg}")
            
            return JsonResponse({
                'code': 500,
                'msg': f'文本生成失败: {error_msg}',
                'data': {
                    'id': record.id,
                    'error': error_msg
                }
            })
        
    except json.JSONDecodeError as e:
        logger.error(f"JSON解析失败: {str(e)}")
        return JsonResponse({
            'code': 400,
            'msg': f'JSON格式错误: {str(e)}',
            'data': None
        })
        
    except Exception as e:
        logger.error(f"文本生成异常: {str(e)}")
        return JsonResponse({
            'code': 500,
            'msg': f'服务器内部错误: {str(e)}',
            'data': None
        })


@login_required
def get_record_detail(request, record_id):
    """获取文本生成记录详情"""
    try:
        # 获取用户（测试时使用默认用户）
        if hasattr(request, 'user') and request.user.is_authenticated:
            user = request.user
        else:
            from django.contrib.auth.models import User
            user, created = User.objects.get_or_create(username='test_user')
        
        record = TextGenerationRecord.objects.get(
            id=record_id, 
            user=user
        )
        return JsonResponse({
            'code': 200,
            'msg': '获取成功',
            'data': {
                'id': record.id,
                'module': record.get_module_display(),
                'content_type': record.get_content_type_display(),
                'language_style': record.get_language_style_display(),
                'prompt': record.prompt,
                'generated_content': record.generated_content,
                'generation_params': record.generation_params,
                'used_model': record.used_model,
                'created_at': record.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'is_favorite': record.is_favorite
            }
        })
    except TextGenerationRecord.DoesNotExist:
        return JsonResponse({
            'code': 404,
            'msg': '记录不存在',
            'data': None
        })


@login_required
@require_http_methods(["POST"])
def toggle_favorite(request, record_id):
    """切换收藏状态"""
    try:
        # 获取用户（测试时使用默认用户）
        if hasattr(request, 'user') and request.user.is_authenticated:
            user = request.user
        else:
            from django.contrib.auth.models import User
            user, created = User.objects.get_or_create(username='test_user')
            
        record = TextGenerationRecord.objects.get(
            id=record_id, 
            user=user
        )
        record.is_favorite = not record.is_favorite
        record.save()
        
        return JsonResponse({
            'code': 200,
            'msg': '收藏状态更新成功',
            'data': {
                'is_favorite': record.is_favorite
            }
        })
    except TextGenerationRecord.DoesNotExist:
        return JsonResponse({
            'code': 404,
            'msg': '记录不存在',
            'data': None
        })


@login_required
@require_http_methods(["POST"])
def delete_record(request, record_id):
    """删除文本生成记录"""
    try:
        # 获取用户（测试时使用默认用户）
        if hasattr(request, 'user') and request.user.is_authenticated:
            user = request.user
        else:
            from django.contrib.auth.models import User
            user, created = User.objects.get_or_create(username='test_user')
            
        record = TextGenerationRecord.objects.get(
            id=record_id, 
            user=user
        )
        record.delete()
        
        return JsonResponse({
            'code': 200,
            'msg': '删除成功',
            'data': None
        })
    except TextGenerationRecord.DoesNotExist:
        return JsonResponse({
            'code': 404,
            'msg': '记录不存在',
            'data': None
        })


@login_required
@require_http_methods(["GET"])
def get_content_types(request):
    """获取模块对应的子类型列表"""
    try:
        module = request.GET.get('module')
        
        # 参数验证
        if not module:
            return JsonResponse({
                'code': 400,
                'msg': '缺少必要参数：module',
                'data': None
            })
        
        # 验证模块类型
        valid_modules = ['creative', 'academic']
        if module not in valid_modules:
            return JsonResponse({
                'code': 400,
                'msg': f'模块类型必须是{valid_modules}之一',
                'data': None
            })
        
        # 根据模块类型筛选内容类型
        content_types = []
        for choice in TextGenerationRecord.CONTENT_TYPE_CHOICES:
            # 创意写作类型
            if module == 'creative' and choice[0] in ['novel', 'poetry', 'script', 'story', 'copy']:
                content_types.append({
                    'value': choice[0],
                    'label': choice[1]
                })
            # 学术写作类型
            elif module == 'academic' and choice[0] in ['paper', 'summary', 'reference', 'report']:
                content_types.append({
                    'value': choice[0],
                    'label': choice[1]
                })
        
        return JsonResponse({
            'code': 200,
            'msg': '获取成功',
            'data': {
                'content_types': content_types
            }
        })
    except Exception as e:
        logger.error(f"获取内容类型列表异常: {str(e)}")
        return JsonResponse({
            'code': 500,
            'msg': f'服务器内部错误: {str(e)}',
            'data': None
        })


@login_required
@require_http_methods(["GET"])
def get_prompt_template(request):
    """获取内容类型的提示词模板"""
    try:
        content_type = request.GET.get('content_type')
        language_style = request.GET.get('language_style', 'casual')
        
        # 参数验证
        if not content_type:
            return JsonResponse({
                'code': 400,
                'msg': '缺少必要参数：content_type',
                'data': None
            })
        
        # 验证内容类型
        valid_content_types = [choice[0] for choice in TextGenerationRecord.CONTENT_TYPE_CHOICES]
        if content_type not in valid_content_types:
            return JsonResponse({
                'code': 400,
                'msg': f'内容类型必须是{valid_content_types}之一',
                'data': None
            })
        
        # 验证语言风格
        valid_language_styles = [choice[0] for choice in TextGenerationRecord.LANGUAGE_STYLE_CHOICES]
        if language_style not in valid_language_styles:
            return JsonResponse({
                'code': 400,
                'msg': f'语言风格必须是{valid_language_styles}之一',
                'data': None
            })
        
        # 获取提示词模板
        try:
            template = PromptTemplate.objects.get(content_type=content_type, language_style=language_style, is_active=True)
            template_text = template.template
        except PromptTemplate.DoesNotExist:
            # 如果没有找到特定语言风格的模板，尝试获取默认的随意风格模板
            try:
                template = PromptTemplate.objects.get(content_type=content_type, language_style='casual', is_active=True)
                template_text = template.template
            except PromptTemplate.DoesNotExist:
                # 如果还没有找到模板，返回默认模板
                template_text = "请写一篇关于{topic}的{content_type}，要求内容详实，结构清晰。"
        
        return JsonResponse({
            'code': 200,
            'msg': '获取成功',
            'data': {
                'template': template_text
            }
        })
    except Exception as e:
        logger.error(f"获取提示词模板异常: {str(e)}")
        return JsonResponse({
            'code': 500,
            'msg': f'服务器内部错误: {str(e)}',
            'data': None
        })
